import { defineStore } from "pinia";
import {ref,computed} from 'vue'

import { getCurrentDate,initList} from '@/utils/index'

export const useCalendarStore = defineStore('calendar',() => {
    //当前日期
    const currentDate = getCurrentDate() //{year: 2024, month: 5, date: 7}

    //选中日期
    const selectedDate = ref(currentDate)

    // //选中的年
    // const year = computed(() => selectedDate.value.year)

    // //选中的月
    // const month = computed(() => selectedDate.value.month)

    // //选中的日
    // const date = computed(() => selectedDate.value.date)
    //================================================================
    //由于select是双向绑定的
    // 因此, 对year和month要使用可写的计算属性

    //选中的年
    const year = computed({
        get:() => selectedDate.value.year,
        set:(value) => {
            selectedDate.value.year = value
        }
    })

    //选中的月
    const month = computed({
        get:() => selectedDate.value.month,
        set:(value) => {
            selectedDate.value.month = value
        }
    })

    //选中的日
    const date = computed({
        get:() => selectedDate.value.date,
        set:(value) => {
            selectedDate.value.date = value
        }
    })

    //计算日期表========
    const lists = computed (() => {
        return initList(year.value,month.value)
    })

    const formatDate = computed(() => {
        return `${year.value}-${month.value}-${date.value}`
    })

    //操作上个月
    const lastMonth = () => {
        if(month.value-- <= 1){
            year.value--
            month.value = 12
        }
    }

    //操作下个月
    const nextMonth = () => {
        if(month.value++ >= 12){
            year.value++
            month.value = 1
        }
    }

    const backToToday = () => {
        selectedDate.value = getCurrentDate()
    }

    return{
        year,
        month,
        date,
        lists,
        formatDate,
        lastMonth,
        nextMonth,
        backToToday,
    }
})